package ds.tree;

public class DiameterOfTree {
	private static class TreeNode{
		int value;
		TreeNode left = null;
		TreeNode right = null;
		
		TreeNode(int val){
			this.value = val;
		}
		
		public String toString(){
			return String.valueOf(value);
		}
	}
	
	private int height(TreeNode node){
		if(node == null){
			return 0;
		}
		return Math.max(height(node.left) +1, height(node.right)+1);
	}
	
	private int diameter(TreeNode node){
		if(node == null){
			return 0 ;
		}
		int lheight = height(node.left);
		int rheight = height(node.right);
		
		int ldiameter = diameter(node.left);
		int rdiameter = diameter(node.right);
		
		return Math.max(lheight+rheight+1,Math.max(ldiameter, rdiameter));
	}
	private static TreeNode tree(){
		TreeNode A = new TreeNode(1);
		TreeNode B = new TreeNode(2);
		TreeNode C = new TreeNode(3);
		TreeNode D = new TreeNode(4);
		TreeNode E = new TreeNode(5);
		
		A.left = B;
		A.right = C;
		B.left = D;
		B.right = E;
		
		return A;
	}
	public static void main(String[] args) {
		DiameterOfTree dia  = new DiameterOfTree();
		System.out.println("Diameter of Tree = " + dia.diameter(tree()));
	}

}
